package com.fyt.video.project.util;

import cc.eguid.FFmpegCommandManager.FFmpegManager;
import cc.eguid.FFmpegCommandManager.FFmpegManagerImpl;
import com.fyt.video.project.VideoClient;
import com.fyt.video.project.pojo.Device;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.net.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
 * @Date 2020/8/10 8:27
 * @Author wsh
 * @Desc 视频播放核心代码
 * @Param device appName
 * @Return Map<String,String>
 */
@Component
public class VideoUtil {
    public static void main(String[] args) {
        VideoUtil videoUtil = new VideoUtil();
        Device device = new Device();
        device.setIp("192.168.1.103");
        device.setAccount("admin");
        device.setPassword("wsh123456");
        device.setPort("8000");
        videoUtil.startTranscodeAndGetTask(device,"hik");
    }

    private static FFmpegManager manager = new FFmpegManagerImpl(10);
    private VideoClient videoClient = new VideoClient();

    public Map<String,String> startTranscodeAndGetTask(Device device,String appName){
        Map<String,String> result = new HashMap<>();
        int code = 0;
        String[] resultNames = {"成功","初始化失败","注册前请关闭预览","注册失败","通道获取失败"};
        if (videoClient.initDevices() == 1){
            code = 1;       //初始化失败
        }
        int regSuc = videoClient.deviceRegister(device.getAccount(), device.getPassword(), device.getIp(), device.getPort());
        if (regSuc != 0){
            code = 3;       //注册失败
        }
        int channelNumber = videoClient.getChannelNumber();
        if (channelNumber == -1){
            code = 4;       //通道获取失败
        }
        if (code == 0){
            String s = VideoUtil.startTranscoding(appName, device.getAccount(), device.getPassword(), device.getIp(), channelNumber);
            result.put("task", StringUtils.isEmpty(s) ? appName : s);
        }else {
            result.put("msg",resultNames[code]);
        }
        //注销
        videoClient.shutDownDev();
        return result;
    }

    /**
     * 使用ffmpeg转换流,nginx推流
     * */
    public static String startTranscoding(String appName,String name,String password,String ip,int channelNumber){
        String channelNumberStr = "ch" + channelNumber;
        if (manager == null){
            manager = new FFmpegManagerImpl(10);
        }
        //判断进程是否存在
        if (VideoUtil.taskIsRun(appName)){
            return appName;     //如果进程存在，则直接返回进程名称
        }
        Map<String,String> map = new HashMap<>();
        map.put("appName",appName);
        map.put("input","rtsp://" + name + ":" + password + "@" +
                ip + ":554/h264/" + channelNumberStr +
                "/main/av_stream");//组装rtsp地址
        map.put("output","rtmp://127.0.0.1:1935/live/");//rtmp流地址
        map.put("codec","h264");
        map.put("fmt","flv");
        map.put("fps","25");
        map.put("rs","640x360");
        map.put("twoPart", "1");
        return manager.start(map);
    }

    /**
     * 关闭进程
     * */
    public boolean stopTranscoding(String task){
        if (VideoUtil.taskIsRun(task)){
            return manager.stop(task);
        }
        //没在运行
        return false;
    }

    /**
     * 判断当前流是否存在
     * 进程名称为0时表示进程不存在
     * */
    public static boolean taskIsRun(String appName){
        return (manager.queryAll().size() > 0 && manager.query(appName) != null);
    }
    /**
     * 获取ip地址
     */
    public static String getServerIP(){
        String sysType = System.getProperties().getProperty("os.name");
        String ip;
        if (sysType.toLowerCase().startsWith("win")){//如果是windows系统，获取ip地址
            String localIP = null;
            try {
                localIP = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            if (localIP != null){
                return localIP;
            }else {
                ip = getIpByEthNum("etho");
                if (ip != null){
                    return ip;
                }
            }
        }
        return "获取服务器IP错误";
    }

    /**
     * 根据忘了接口获取ip地址
     * */
    private static String getIpByEthNum(String ethNum){
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip;
            while(allNetInterfaces.hasMoreElements()){
                NetworkInterface networkInterface = (NetworkInterface)allNetInterfaces.nextElement();
                if (ethNum.equals(networkInterface.getName())){
                    Enumeration addresses = networkInterface.getInetAddresses();
                    while (addresses.hasMoreElements()){
                        ip = (InetAddress)addresses.nextElement();
                        if (ip != null && ip instanceof Inet4Address){
                            return ip.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "获取服务器ip错误";
    }
}
